package com.frinder.hadoop.job.electricity;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

/**
 * @author frinder
 * @date 2018/6/25
 * @Description: ${todo}
 */
@Slf4j
public class ElectricityCountJob {

    public void run(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        Job job = Job.getInstance(conf, "max_electricity_units");
        job.setJarByClass(ElectricityCountJob.class);
        job.setMapperClass(ElectricityMapper.class);
        job.setReducerClass(ElectricityReducer.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        String inputPathStr = otherArgs[0];
        String outputPathStr = otherArgs[1];
        log.info("Input:{} Output: {}", inputPathStr, outputPathStr);

        FileInputFormat.setInputPaths(job, new Path(inputPathStr));

        // 删除 out目录
        Path outputPath = new Path(outputPathStr);
        FileSystem fileSystem = outputPath.getFileSystem(conf);
        if (fileSystem.exists(outputPath)) {
            log.info("Output: {} exists, delete it !", outputPathStr);
            fileSystem.delete(outputPath, true);
        }
        FileOutputFormat.setOutputPath(job, new Path(outputPathStr));

        boolean result = job.waitForCompletion(true);
        log.info("Result: {}", result);
    }

}
